//
//  FlieUploadManager.m
//  KEREN
//
//  Created by MW on 2023/4/14.
//

#import "FlieUploadManager.h"
#import "OSSService.h"
@interface FlieUploadManager()
@property (nonatomic,strong) NSString *bucketName;
@property (nonatomic,strong) OSSClient *client;
@end

@implementation FlieUploadManager
+ (instancetype)shareInstance {
    static FlieUploadManager *manager;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[self alloc]init];
    });
    return manager;
}

#pragma mark - 初始化oss
- (void)getossToken{
    [NetworkingTool GET:get_oss_token parameters:@{} isDeviceUrl:YES success:^(id  _Nonnull response, NSURLSessionDataTask * _Nonnull operation) {
        DDLogInfo(@"=====getossToken %@",response);
        id<OSSCredentialProvider> credential = [[OSSFederationCredentialProvider alloc] initWithFederationTokenGetter:^OSSFederationToken * _Nullable{
            OSSFederationToken *token = [OSSFederationToken new];
            // 从STS服务获取的临时访问密钥（AccessKey ID和AccessKey Secret）。
            token.tAccessKey = response[@"data"][@"access_key"];
            token.tSecretKey = response[@"data"][@"access_secret"];
            // 从STS服务获取的安全令牌（SecurityToken）。
            token.tToken = response[@"data"][@"security_token"];
            // 临时访问凭证的过期时间。
            token.expirationTimeInGMTFormat = @"90";
            return token;
        }];
        if(response && [response isKindOfClass:[NSDictionary class]]  && response[@"data"] && [response[@"data"] isKindOfClass:[NSDictionary class]] && response[@"data"][@"bucket"]){
            self.bucketName = response[@"data"][@"bucket"];
        }
        self.client = [[OSSClient alloc] initWithEndpoint:@"https://oss-cn-hangzhou.aliyuncs.com" credentialProvider:credential];
    } failure:^(NSError * _Nonnull error, NSURLSessionDataTask * _Nonnull operation) {
        
    }];
}

- (void)uploadImagesToOss:(NSArray *)imgs type:(NSInteger )type{
    _currentIndex = 0;
    [self.imgsArrM removeAllObjects];
    for (int i = 0; i < imgs.count; i ++) {
        UIImage *img = imgs[i];
        NSData *imageData = UIImageJPEGRepresentation(img,0.5);
        [[KRAlartManager shareInstance] showLodingAlertView:@"努力加载中..."];
        [[FlieUploadManager shareInstance] uploadImageToOss:imageData type:type andCount:imgs.count currentCount:i];
    }
}
- (void)uploadImageToOss:(NSData *)imageData type:(NSInteger )type andCount:(NSInteger)count currentCount:(NSInteger)currentCount{
    WEAKSELF
    OSSPutObjectRequest * put = [OSSPutObjectRequest new];
    put.bucketName = self.bucketName;
    if(type == 0){
        put.objectKey = [NSString stringWithFormat:@"keren/%ld_user.png",[[DeteManager shareInstance] getCurrentDay]];
    }else if(type == 1){
        put.objectKey = [NSString stringWithFormat:@"keren/%ld_device.png",[[DeteManager shareInstance] getCurrentDay]];
    }else if(type == 2){
        put.objectKey = [NSString stringWithFormat:@"keren/%ld_%ld_feedback_creat.png",[[DeteManager shareInstance] getCurrentDay],currentCount];
    }else if(type == 3){
        put.objectKey = [NSString stringWithFormat:@"keren/%ld_%ld_repair_creat.png",[[DeteManager shareInstance] getCurrentDay],currentCount];
    }
    put.uploadingData = imageData;
    OSSTask *putTask = [self.client putObject:put];
    [putTask continueWithBlock:^id _Nullable(OSSTask * _Nonnull task) {
        if(!task.error){
    
            OSSPutObjectResult * result = task.result;
            NSString *urlStr = [NSString stringWithFormat:@"%@",put.objectKey];
            if(type == 0){
                [self updatePhoto:urlStr];
            }else if (type == 1){
                [self updetaDeviceImage:urlStr];
            }else if(type == 2 || type == 3){
                weakSelf.currentIndex ++;
                [weakSelf.imgsArrM addObject:urlStr];
                if(weakSelf.currentIndex == count){
                    [[NSNotificationCenter defaultCenter] postNotificationName:IMGSUPLOADFINISH object:nil];
                }
            }
            NSLog(@"%@ -- upload object success!",result);
        }else{
            if(type == 2 || type == 3){
                weakSelf.currentIndex ++;
                if(weakSelf.currentIndex == count){
                    [[NSNotificationCenter defaultCenter] postNotificationName:IMGSUPLOADFINISH object:nil];
                }
            }else{
                [[KRAlartManager shareInstance] hidenLodingImageView];
            }
     
            NSLog(@"upload object failed, error: %@" , task.error);
        }
        return nil;
    }];
}

- (void)updatePhoto:(NSString *)urlString{
    if(urlString > 0){
        [NetworkingTool POST:User_update parameters:@{@"picture":urlString} isDeviceUrl:NO success:^(id  _Nonnull response, NSURLSessionDataTask * _Nonnull operation) {
            if([response[@"code"] intValue] == 0){
                [[KRAlartManager shareInstance] hidenLodingImageView];
                NSMutableDictionary *dict = [NSMutableDictionary dictionary];
                [dict setDictionary:[[NSUserDefaults standardUserDefaults] valueForKey:USERINFOKEY]];
                [dict setObject:urlString forKey:@"picture"];
                [[NSUserDefaults standardUserDefaults] setObject:dict forKey:USERINFOKEY];
                [[[ClassManager shareInstance] currentViewController].navigationController popToRootViewControllerAnimated:YES];
            }else{
                
            }
        } failure:^(NSError * _Nonnull error, NSURLSessionDataTask * _Nonnull operation) {
            
        }];
    }else{
        [[KRAlartManager shareInstance] showErrorAlert:@"图片上传失败"];
    }
}

- (void)pushFeedbackCreate:(NSArray *)imgs{
    
}

- (void)updetaDeviceImage:(NSString *)urlString{
    DeviceInfo *info = [UserInfoManager sharedInstance].currentDeviceInfo;
    NSDictionary *parameters = @{@"ebike_id":@(info.Id),@"ebike_image":urlString};
    [NetworkingTool POST:Device_message_update parameters:parameters isDeviceUrl:YES success:^(id  _Nonnull response, NSURLSessionDataTask * _Nonnull operation) {
        if([response[@"code"] intValue] == 0){
            [[KRAlartManager shareInstance] hidenLodingImageView];
            [[[ClassManager shareInstance] currentViewController].navigationController popToRootViewControllerAnimated:YES];
        }else{

        }
    } failure:^(NSError * _Nonnull error, NSURLSessionDataTask * _Nonnull operation) {
        
    }];
}


- (NSMutableArray *)imgsArrM{
    if(!_imgsArrM){
        _imgsArrM = [NSMutableArray array];
    }
    return _imgsArrM;
}

@end
